<template>
  <div>
    <div class="topSearch">
      <div class="title">
        <span
            style="
            width: 3px;
            height: 20px;
            background-color: #0f79e2;
            margin-right: 8px;
          "
        ></span
        ><span>预售单库存</span>
      </div>
      <div class="search">
        <span>名称：</span>
        <el-input
            size="small"
            clearable
            style="width: 250px"
            v-model="params.productName"
            placeholder="请输入名称"
        ></el-input>
        <span>编码：</span>
        <el-input
            size="small"
            clearable
            style="width: 250px"
            v-model="params.productCode"
            placeholder="请输入编码"
        ></el-input>
        <span>所属仓库：</span>
        <el-select
            clearable
            v-model="params.area"
            size="small"
            style="width: 200px"
            placeholder="请选择"
        >
          <el-option
              v-for="item in warehouseList"
              :key="item.area"
              :label="item.areaName"
              :value="item.area"
          />
        </el-select>
        <span>选择日期：</span>
        <el-date-picker
            v-model="sateValue"
            type="daterange"
            range-separator="至"
            clearable
            size="small"
            @change="selectTime"
            style="width: 250px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button
            size="small"
            type="primary"
            style="width: 80px; margin-left: 20px"
            @click="searchFn"
        >查询
        </el-button>
        <el-button
            size="small"
            style="width: 80px; margin-left: 20px"
            @click="reset"
        >重置
        </el-button>
        <el-dropdown style="margin-left: 15px" @command="exportExcel">
          <el-button type="primary" size="small">
            导出<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="part">缺货导出</el-dropdown-item>
            <el-dropdown-item command="isPage">当前页导出</el-dropdown-item>
            <el-dropdown-item command="all">全量导出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="centerTable">
      <el-table
          :data="persaleData"
          border
          height="calc(100vh - 350px)"
          :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
          v-loading="loading"
          :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="productName" label="单品名称"/>
        <el-table-column prop="productCode" label="编码"/>
        <el-table-column prop="norms" label="规格"/>
        <el-table-column prop="area" label="仓库">
          <template slot-scope="scope">
            <div v-if="scope.row.area === 56"><span>西安2仓</span></div>
            <div v-if="scope.row.area === 58"><span>山西仓</span></div>
          </template>
        </el-table-column>
        <el-table-column prop="productNum" label="数量"/>
        <el-table-column prop="stock" label="现有库存"/>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
import * as XLSX from "xlsx-js-style";

export default {
  name: "isPerSale",
  data() {
    return {
      warehouseList: [],
      persaleData: [],
      loading: false,
      sateValue: "",
      currentPage: 1,
      totalCount: 0,
      params: {
        startTime: "",
        endTime: "",
        productName: "",
        productCode: "",
        area: '',
        pageSize: 20,
        pageNumber: 1
      }
    }
  },
  created() {
    this.$api.areaLedgerAreaList().then(res => {
      this.warehouseList = res
    })
    this.getpersaleList()
  },
  methods: {
    selectTime(val) {
      if (val) {
        this.params.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.params.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.params.startTime = ''
        this.params.endTime = ''
      }
    },
    searchFn() {
      this.params.pageNumber = 1
      this.getpersaleList()
    },
    getpersaleList() {
      const params = this.params
      this.$api.orderGetPerOrderList(params).then(res => {
        this.persaleData = res.data
        this.totalCount = res.total
      })
    },
    reset() {
      this.params = this.$options.data.call(this).params
      this.sateValue = ""
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getpersaleList()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getpersaleList()
    },
    async exportExcel(val) {
      const dataArr = await this.$api.orderGetPerOrderList({pageSize: 10000, pageNumber: 1}).then()
      let downData = []
      if (val === 'part') {
        // 只保留 stock 小于 1000 的数据
        downData = dataArr.data.filter(item => item.stock < 1000);
      } else if (val == 'isPage') {
        const dataS = await this.$api.orderGetPerOrderList({
          pageSize: this.params.pageSize,
          pageNumber: this.params.pageNumber,
          area: this.params.area
        }).then()
        downData = dataS.data
      } else {
        downData = dataArr.data
      }
      const wb = XLSX.utils.book_new();
      let data = [
        [`${val}预售单库存`],
        ['单品名称', '编码', '仓库', '数量', '现有库存']
      ];
      downData.forEach(el => {
        let warehouseName = ""
        if (el.area == 56) warehouseName = '西安2仓';
        if (el.area == 58) warehouseName = '山西仓';
        data.push([
          el.productName,
          el.productCode,
          warehouseName,
          el.productNum,
          el.stock,
        ]);
      });

      const ws = XLSX.utils.aoa_to_sheet(data);
      const style = {
        alignment: {horizontal: 'center'},
        font: {bold: true, color: {rgb: '000000'}},
        fill: {fgColor: {rgb: '3CB371'}}
      };
      const range = ['A2', 'B2', 'C2', 'D2', 'E2']; // 目标单元格范围
// 遍历每个单元格并应用样式
      range.forEach(cell => {
        ws[cell].s = style;
      });
      ws["A1"].s = {
        alignment: {horizontal: 'center'},
        font: {bold: true, color: {rgb: '000000'}},
        fill: {fgColor: {rgb: 'ff6a00'}}
      }
      // // 设置列宽
      // ws['!cols'] = Array(6).fill({wpx: 150});
      // Object.keys(ws).forEach(cell => {
      //   if (cell[0] !== '!') { // 排除特殊属性，如 `!ref`
      //     if (!ws[cell].s) {
      //       ws[cell].s = {}; // 确保 `s` 存在
      //     }
      //     if (!ws[cell].s.alignment) {
      //       ws[cell].s.alignment = {};
      //     }
      //     ws[cell].s.alignment.horizontal = 'center';
      //   }
      // });
      // 合并标题行
      let merges = [{s: {r: 0, c: 0}, e: {r: 0, c: 4}}];

      ws['!merges'] = merges;
      // 追加 Sheet 到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '提成汇总');

      // 生成 Excel 文件
      const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});

      // 创建 Blob 并下载
      const blob = new Blob([this.s2ab(wbout)], {type: 'application/octet-stream'});
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${val}预售单库存.xlsx`;

      // 触发下载
      document.body.appendChild(link);
      link.click();

      // 清理 URL 对象，防止内存泄漏
      setTimeout(() => {
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }, 100);
    },

// 转换字符串到 ArrayBuffer
    s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xff;
      }
      return buf;
    }
  }
}
</script>

<style scoped lang="less">
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }
}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}
</style>